package com.xiaoKe.zhonghzu.global.base;

import android.content.Context;
import android.view.View;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class DynamicSpanGridLayoutManager extends GridLayoutManager {

    private int maxSpanCount;
    private int itemMinWidth;
    private boolean isMeasuring = true;

    public DynamicSpanGridLayoutManager(Context context, int maxSpanCount, int itemMinWidth) {
        super(context, maxSpanCount);
        this.maxSpanCount = maxSpanCount;
        this.itemMinWidth = itemMinWidth;
    }

    @Override
    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
        super.onLayoutChildren(recycler, state);

        // Call measureChildren only if needed
        if (isMeasuring) {
            measureChildren(recycler, state);
        }
    }

    private void measureChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
        if (getItemCount() == 0) {
            return;
        }

        View child = recycler.getViewForPosition(0);
        addView(child);
        measureChild(child, View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int measuredWidth = getDecoratedMeasuredWidth(child);

        int screenWidth = getHorizontalSpace();
        int spanWidth = screenWidth / maxSpanCount;
        int newSpanCount = Math.max(1, Math.min(maxSpanCount, screenWidth / Math.max(measuredWidth, itemMinWidth)));

        setSpanCount(newSpanCount);
        isMeasuring = false; // Measurement done, no need to repeat

        detachView(child); // Detach the measured view since it's just for measurement
    }

    private int getHorizontalSpace() {
        return getWidth() - getPaddingLeft() - getPaddingRight();
    }

    // Call this method when adapter data changes to reset measurement flag
    public void resetMeasurement() {
        isMeasuring = true;
        requestLayout();
    }

    @Override
    public void onLayoutCompleted(RecyclerView.State state) {
        super.onLayoutCompleted(state);
        // Force measure when layout is completed
        resetMeasurement();
    }
}